//
//  KnowledgeManager.m
//  Grammar
//
//  Created by Rick on 7/3/13.
//
//

#import "KnowledgeManager.h"
#import "Knowledge.h"

#define TYKnowledge @"TYKnowledge"
#define TYKnowledgeManagerArchiver  @"TYKnowledgeManagerArchiver"

@interface KnowledgeManager()
- (void)restore;
@end

@implementation KnowledgeManager
static KnowledgeManager *_sharedInst = nil;

+(KnowledgeManager*)sharedManager
{
    @synchronized(self) {
        if (_sharedInst == nil) {
            _sharedInst = [[self alloc] init];
        }
    }
    return _sharedInst;
}

- (id)init
{
    if ((self = [super init])) {
        [self restore];
    }
    return self;
}

- (void)saveData{
    if (_knowledges) {
        NSMutableData *data = [[NSMutableData alloc] init];
        NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]
                                     initForWritingWithMutableData:data];
        [archiver encodeObject:_knowledges forKey:TYKnowledgeManagerArchiver];
        [archiver finishEncoding];
        [USER_DEFAULT setObject:data forKey:[NSString stringWithFormat:@"%@%@",TYKnowledge,_knowledgeType] ];
        [archiver release];
        [data release];
        
        [USER_DEFAULT synchronize];
    }
}

- (void)readData{
    NSData *data = [USER_DEFAULT objectForKey:[NSString stringWithFormat:@"%@%@",TYKnowledge,_knowledgeType]];;
    if (!data) {
        return;
    }
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    NSArray *array = [unarchiver decodeObjectForKey:TYKnowledgeManagerArchiver];
    [unarchiver finishDecoding];
    [_knowledges addObjectsFromArray:array];
    [unarchiver release];
}

- (void)addKnowledge:(Knowledge *)knowledge
{
    for (Knowledge *aknowledge in self.knowledges) {
        if ([aknowledge.knowledgeId isEqualToString:knowledge.knowledgeId]) {
            return;
        }
    }
    [_knowledges insertObject:knowledge atIndex:0];
    
    [self saveData];
}

- (void)removeKnowledge:(Knowledge *)knowledge
{
    NSArray *array = [NSArray arrayWithArray:self.knowledges];
    for (Knowledge *aknowledge in array) {
        if ([aknowledge.knowledgeId isEqualToString:knowledge.knowledgeId]) {
            [_knowledges removeObject:aknowledge];
            [self saveData];
        }
    }
}

- (NSMutableArray*)knowledges
{
    [self clearMemoryData];
    [self readData];
    return _knowledges;
}

- (void)restore
{
    self.knowledges = [NSMutableArray array];
    [self readData];
}

- (void)clearMemoryData
{
    [_knowledges removeAllObjects];
}

- (void)removeAllKnowledges
{
    [_knowledges removeAllObjects];
    [USER_DEFAULT removeObjectForKey:[NSString stringWithFormat:@"%@%@",TYKnowledge,_knowledgeType]];
    [USER_DEFAULT synchronize];
}
@end
